package me.znext.learn.android;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import me.znext.learn.android.db.NoteDAO;

import java.util.ArrayList;

public class MyNoteActivity extends AppCompatActivity {
  private NoteDAO noteDAO;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my_note);

    this.setTitle("我的便签");
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    showNotes();

    Button saveButton = (Button) findViewById(R.id.saveButton);
    assert saveButton != null;
    final EditText noteEditText = (EditText) findViewById(R.id.noteEditText);
    saveButton.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        String note = String.valueOf(noteEditText.getText());
        if (note.equals("")) {
          Notice.alert(MyNoteActivity.this, "请输入便签内容");
        } else {
          noteDAO.add(note);
          showNotes();
          noteEditText.setText("");
        }
      }
    });
  }

  private void showNotes() {
    noteDAO = new NoteDAO(this);
    ArrayList myNotes = noteDAO.getAllNote();
    String[] from = new String[] {"time", "text"};
    int[] to = new int[] {R.id.time, R.id.text};
    SimpleAdapter adapter = new SimpleAdapter(this, myNotes, R.layout.item_note, from, to);

    ListView noteList = (ListView) findViewById(R.id.noteList);
    assert noteList != null;
    noteList.setAdapter(adapter);
  }
}
